/**
 */
package com.AliCloudMobile;

import org.apache.cordova.CallbackContext;
import org.apache.cordova.CordovaInterface;
import org.apache.cordova.CordovaPlugin;
import org.apache.cordova.CordovaWebView;
import org.apache.cordova.PluginResult;
import org.apache.cordova.PluginResult.Status;
import org.json.JSONObject;
import org.json.JSONArray;
import org.json.JSONException;
import android.content.Context;


import android.app.Activity;
import android.app.ProgressDialog;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Intent;
import android.os.Bundle;
import android.text.method.ScrollingMovementMethod;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.Nullable;
import android.graphics.Color;


import com.mobile.auth.gatewayauth.AuthUIConfig;
import com.mobile.auth.gatewayauth.PhoneNumberAuthHelper;
import com.mobile.auth.gatewayauth.ResultCode;
import com.mobile.auth.gatewayauth.TokenResultListener;
import com.mobile.auth.gatewayauth.model.TokenRet;
import com.mobile.auth.gatewayauth.PreLoginResultListener;
import com.mobile.auth.gatewayauth.PnsLoggerHandler;

import android.util.Log;

public class AliCloudMobile extends CordovaPlugin {
  private static final String TAG = "AliCloudMobile";
  private PhoneNumberAuthHelper mPhoneNumberAuthHelper;
  private TokenResultListener mTokenResultListener;

  private void initializePhoneNumberAuthHelper() {
    mPhoneNumberAuthHelper = PhoneNumberAuthHelper.getInstance(cordova.getActivity(), mTokenResultListener);
    mPhoneNumberAuthHelper.getReporter().setLoggerEnable(true);
  }

  public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {
    switch (action) {
      case "setAuthSDKInfo":
        setAuthSDKInfo(args.getString(0), args.getJSONObject(1).toString(), callbackContext);
        return true;
      case "getLoginToken":
        getLoginToken(args.getInt(0), callbackContext);
        return true;
      case "cancelLogin":
        cancelLogin(callbackContext);
        return true;
      case "accelerateLoginPage":
        accelerateLoginPage(args.getInt(0), callbackContext);
        return true;
      case "checkEnvironment":
        checkEnvironment(args.getString(0), callbackContext);
        return true;
      case "isChinaMobile":
        isChinaMobile(callbackContext);
        return true;
      case "isChinaTelecom":
        isChinaTelecom(callbackContext);
        return true;
      case "getCurrentCarrierName":
        getCurrentCarrierName(callbackContext);
        return true;
      case "simSupportedIsOK":
        simSupportedIsOK(callbackContext);
        return true;
      case "getUniqueID":
        getUniqueID(callbackContext);
        return true;
      default:
          return false;
    }
  }

  private void setAuthSDKInfo (String sdkInfo, String languageInfoStr, CallbackContext callbackContext) {
    JSONObject languageInfo;
    try {
        languageInfo = new JSONObject(languageInfoStr);
    } catch (JSONException e) {
        callbackContext.error("Invalid languageInfo JSON");
        return;
    }
    mTokenResultListener = new TokenResultListener() {
        @Override
        public void onTokenSuccess(String s) {
            TokenRet tokenRet = null;
            try {
                tokenRet = TokenRet.fromJson(s);

                if (ResultCode.CODE_SUCCESS.equals(tokenRet.getCode())) {
                  // 获取token成功
                  callbackContext.success(s);
                  mPhoneNumberAuthHelper.quitLoginPage();
                  mPhoneNumberAuthHelper.setAuthListener(null);
                }   
            } catch (Exception e) {
                e.printStackTrace();
                Log.i(TAG, "onTokenSuccess e" + e);
                callbackContext.error("onTokenSuccess 出错了e="+e);
            }
        }

        @Override
        public void onTokenFailed(String s) {
            TokenRet tokenRet = null;
            try {
                tokenRet = TokenRet.fromJson(s);
                if (ResultCode.CODE_ERROR_USER_CANCEL.equals(tokenRet.getCode())) {
                    //模拟的是必须登录 否则直接退出app的场景
                } else {
                  Log.i(TAG, "一键登录失败切换到其他登录方式" + s);
                  callbackContext.success(s);
                }
            } catch (Exception e) {
                e.printStackTrace();
                Log.i(TAG, "onTokenFailed 错误Exception" + e);
                callbackContext.error("onTokenFailed 出错了e="+e);

            }
            mPhoneNumberAuthHelper.quitLoginPage();
            mPhoneNumberAuthHelper.setAuthListener(null);
        }
    };
    mPhoneNumberAuthHelper = PhoneNumberAuthHelper.getInstance(cordova.getActivity(), mTokenResultListener);
    // 选调方法：控制台日志输出开关
    mPhoneNumberAuthHelper.getReporter().setLoggerEnable(true);
    // 必调方法：设置SDK密钥
    mPhoneNumberAuthHelper.setAuthSDKInfo(sdkInfo);


    String sloganText = languageInfo.optString("sloganText", "本机号码可一键登录");
    String loginButtonText = languageInfo.optString("loginButtonText", "一键登录/注册");
    String switchAccText = languageInfo.optString("switchAccText", "返回到上一页");

    // 修改授权页主题，该接口需在getLoginToken接口之前调用
    mPhoneNumberAuthHelper.setAuthUIConfig(new AuthUIConfig.Builder()
          // 状态栏
          .setWebViewStatusBarColor(Color.parseColor("#f5f2f0")) // 设置协议页状态栏颜色（系统版本5.0以上可设置）不设置则与授权页设置一样）

          // 导航栏
          .setNavHidden(true) // 设置导航栏是否隐藏
          .setNavReturnHidden(true) //  设置导航栏返回按钮是否隐藏/ 隐藏导航栏返回按钮
          // .setNavText("") // 设置导航栏标题文字内容 
          // .setNavTextColor(Color.parseColor("#303138")) // 设置导航栏标题文字颜色
          // .setNavTextSize(16)  // 设置导航栏标题文字大小 
          .setWebNavColor(Color.parseColor("#FFC600"))  //设置协议页顶部导航栏背景色，不设置则与授权页一致 
          // .setNavReturnImgPath("commonback") // 设置导航栏返回键图片
          // #191c23
          .setWebNavTextColor(Color.parseColor("#ffffff"))  // 设置协议页顶部导航栏标题颜色，不设置则与授权页一致


          // Logo区
          .setLogoHidden(false) // 设置Logo是否隐藏
          .setLogoImgPath("logo2")  // 设置Logo图片路径（即drawable下文件名称，但无需带文件格式）
          .setLogoOffsetY(0) // 设置Logo控件相对导航栏顶部的位移（单位：dp）
          .setLogoWidth(88)   // 设置Logo控件宽度（单位：dp）
          .setLogoHeight(88)  // 设置Logo控件高度（单位：dp）
         
          // Slogan
          .setSloganText(sloganText)  // 设置slogan文字内容
          .setSloganTextColor(Color.parseColor("#0d0d0d"))
          // .setSloganOffsetY(20)  // 设置slogan相对导航栏顶部的位移，单位dp
          .setSloganTextSizeDp(14) // 设置slogan相文字大小，单位dp

          // 掩码栏
          .setNumberColor(Color.parseColor("#0d0d0d")) // 设置掩码字体颜色
          .setNumberSize(22) // 设置掩码字体大小，单位dp
          
          // 登录按钮
          .setLogBtnText(loginButtonText)  // 设置登录按钮文字（文字必须包含“登录”或“注册”）
          .setLogBtnTextColor(Color.parseColor("#ffffff")) // 设置登录按钮文字颜色。
          .setLogBtnTextSize(16)   // 设置登录按钮文字大小，单位dp
          .setLogBtnBackgroundPath("one_phone_login_btn") // 设置登录按钮背景图片路径。
          
          // 切换到其他方式
          .setSwitchAccHidden(false)  // 设置切换按钮点是否可见
          .setSwitchAccText(switchAccText) // 设置切换按钮文字内容
          .setSwitchAccTextColor(Color.parseColor("#9a9a9a")) // 设置切换按钮文字颜色
          .setSwitchAccTextSize(14)   // 设置切换按钮文字大小，单位dp

          // 隐私政策栏
          .setAppPrivacyOne("《用户协议》", "https://www.ruiquejia.com.cn/privacy-cn/user-agreement.html")
          .setAppPrivacyTwo("《隐私政策、儿童隐私保护声明》", "https://www.ruiquejia.com.cn/privacy-cn/privacyAndChildrenPolicy.html")
          .setPrivacyState(false)
          .setAuthPageActIn("in_activity", "out_activity")
          .setAuthPageActOut("in_activity", "out_activity")
          .setProtocolShakePath("protocol_shake")
          // .setVendorPrivacyPrefix("《")
          // .setVendorPrivacySuffix("》")
          // .setAppPrivacyColor(Color.parseColor("#FFC600")) // 设置隐私条款名称颜色（基础文字颜色，协议文字颜色）
          .setPrivacyTextSize(14) // 设置隐私条款文字大小
          .setPrivacyOneColor(Color.parseColor("#FFC600")) // 授权页协议1文本颜色
          .setPrivacyTwoColor(Color.parseColor("#FFC600")) // 授权页协议2文本颜色
          .setPrivacyOperatorColor(Color.parseColor("#FFC600")) // 授权页运营商协议文本颜色
    .create());

    // 登录获取token
    getLoginToken(callbackContext);
  }
  
  private void getLoginToken(CallbackContext callbackContext) {
        mPhoneNumberAuthHelper = PhoneNumberAuthHelper.getInstance(cordova.getActivity(), mTokenResultListener);
        mPhoneNumberAuthHelper.checkEnvAvailable();
        mPhoneNumberAuthHelper.getLoginToken(cordova.getActivity(), 5000);
  }

  private void useLoggerForContext(PhoneNumberAuthHelper mPhoneNumberAuthHelper,CallbackContext callbackContext, String messageFilter) {
    mPhoneNumberAuthHelper.getReporter().setLoggerHandler(new PnsLoggerHandler() {
      @Override
      public void monitor(String msg) {
        Log.e("xxffg", "Monitor:" + msg);
        if (callbackContext != null) {
          callbackContext.success("Monitor:" + msg);
        }
      }
      @Override
      public void verbose(String msg) {
        if (callbackContext != null) {
          callbackContext.success("Verbose:" + msg);
        }
      }
      @Override
      public void info(String msg) {
        Log.e("xxffg", "Info:" + msg);
        if (callbackContext != null && msg.contains(messageFilter)) {
          callbackContext.success("Info:" + msg);
        }
      }
      @Override
      public void debug(String msg) {
        Log.e("xxffg", "Debug:" + msg);
        if (callbackContext != null) {
          callbackContext.success("Debug:" + msg);
        }
      }
      @Override
      public void warning(String msg) {
        Log.e("xxffg", "Warning:" + msg);
        if (callbackContext != null) {
          callbackContext.success("Warning:" + msg);
        }
      }
      @Override
      public void error(String msg) {
        Log.e("xxffg", "Error:" + msg);
        if (callbackContext != null) {
          callbackContext.error("Error:" + msg);
        }
      }
    });
  }


  private void setAuthSDKInfo2(final String sdkInfo, final CallbackContext callbackContext) {
    cordova.getThreadPool().execute(new Runnable() {
      public void run() {
          try {
          initializePhoneNumberAuthHelper();
          mPhoneNumberAuthHelper.setAuthSDKInfo(sdkInfo);
          // callbackContext.success("SDK Info set successfully");
          useLoggerForContext(mPhoneNumberAuthHelper, callbackContext, "getSdkConfig");
        } catch (Exception e) {
          callbackContext.error("Error setting SDK Info: " + e.getMessage());
        }
      }
    });
  }


  // Cordova Plugin Method
  private void getLoginToken(int timeout, CallbackContext callbackContext) {
    try {
      initializePhoneNumberAuthHelper();
      mPhoneNumberAuthHelper.getLoginToken(cordova.getActivity(), timeout);
      useLoggerForContext(mPhoneNumberAuthHelper, callbackContext, "CT_acallback");
    } catch (Exception e) {
      callbackContext.error("Error getting login token: " + e.getMessage());
    }
  }

  // Cordova Plugin Method
  private void accelerateLoginPage(int timeout, final CallbackContext callbackContext) throws JSONException {
    initializePhoneNumberAuthHelper();
    mPhoneNumberAuthHelper.accelerateLoginPage(timeout, new PreLoginResultListener() {
      @Override
      public void onTokenSuccess(String s) {
        callbackContext.success(s);
      }

      @Override
      public void onTokenFailed(String s, String extra) {
        callbackContext.error("Accelerate failed: " + s + ", " + extra);
      }
    });
  }

  private void cancelLogin(CallbackContext callbackContext) {
    try {
      initializePhoneNumberAuthHelper();
      mPhoneNumberAuthHelper.quitLoginPage();
      callbackContext.success("Login Cancelled");
    } catch (Exception e) {
      callbackContext.error("Failed to cancel login: " + e.getMessage());
    }
  }

  private void checkEnvironment(String authType, CallbackContext callbackContext) throws JSONException {
    initializePhoneNumberAuthHelper();
    int serviceType = PhoneNumberAuthHelper.SERVICE_TYPE_LOGIN; // Default to login service type
    mPhoneNumberAuthHelper.checkEnvAvailable();
    useLoggerForContext(mPhoneNumberAuthHelper, callbackContext, "checkEnvAvailable");
  }

  private void isChinaMobile(CallbackContext callbackContext) {
    callbackContext.success("not supported on android");
  }


  private void isChinaTelecom(CallbackContext callbackContext) {
    callbackContext.success("not supported on android");
  }

  private void getCurrentCarrierName(CallbackContext callbackContext) {
    initializePhoneNumberAuthHelper();
    String carrierName = mPhoneNumberAuthHelper.getCurrentCarrierName();
    callbackContext.success(carrierName);
  }


  private void simSupportedIsOK(CallbackContext callbackContext) {
    callbackContext.success("not supported on android");
  }

  private void getUniqueID(CallbackContext callbackContext) {
    callbackContext.success("not supported on android");
  }
}
